package com.stellar.core.service;


import com.stellar.core.code.VerifyCode;
import com.stellar.core.sender.EmailCodeSender;
import com.stellar.core.sender.SmsCodeSender;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;


/**
 * @author Jqcc
 * @version 1.0
 * @date 2025/2/13
 */
@Slf4j
public class VerifyCodeService {

    private final SmsCodeSender smsCodeSender;

    private final EmailCodeSender emailCodeSender;

    private final int codeLength;

    private final int expireSeconds;

    public VerifyCodeService(SmsCodeSender smsCodeSender,
                             EmailCodeSender emailCodeSender,
                             int codeLength,
                             int expireSeconds) {
        this.smsCodeSender = smsCodeSender;
        this.emailCodeSender = emailCodeSender;
        this.codeLength = codeLength;
        this.expireSeconds = expireSeconds;
    }

    /**
     * 生成短信验证码
     *
     * @param phone 手机号
     * @return VerifyCode
     */
    public VerifyCode generateSmsCode(String phone) {
        String code = generateRandomCode();
        Map<String, String> params = new HashMap<>();
        params.put("code", code);
        boolean res = smsCodeSender.send(phone, params);
        if (!res) {
            log.error("发送手机短信验证码失败：{}", code);
            throw new IllegalArgumentException("发送手机短信验证码失败");
        }
        log.info("发送手机短信验证码：{}", code);
        return new VerifyCode(code, expireSeconds);
    }

    /**
     * 生成邮箱验证码
     *
     * @param email 邮箱
     * @return VerifyCode
     */
    public VerifyCode generateEmailCode(String email) {
        String code = generateRandomCode();
        emailCodeSender.send(email, code);
        return new VerifyCode(code, expireSeconds);
    }


    /**
     * 生成随机验证码
     *
     * @return 验证码
     */
    private String generateRandomCode() {
        return String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10, codeLength - 1)));
    }
}